<template>
  <div class="sanitationStation-box" id="sanitationStation">
    <div style="height: 50%;" ref="time"></div>
    <div style="height: 50%;" ref="area"></div>
  </div>
</template>
<script>
import * as echarts from "echarts";

const getBaseOptions = () => {
  return {
    color: ["#153238"],
    legend: {
      show: false,
      top: "0%",
      itemWidth: 10, // 图例标记的图形宽度
      itemHeight: 8, // 图例标记的图形高度
      textStyle: {
        color: "#fff",
        fontSize: 10,
      },
    },
    grid: {
      top: "5%",
      bottom: "16%",
      left: '9%',
      right: "0%",
    },
    yAxis: {
      axisLine: {
        show: false,
      },
      axisLabel: {
        show: true,
        lineStyle: {
          color: "#fff",
        },
        nameTextStyle: {
          color: "#fff",
          fontSize: '9',
        },
      },
      axisTick: {
        show: false,
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: "#2E6EE7",
          type: 'dashed',
        },
      },
    },
  };
};

const getBaseXAxis = (data, labelShow,axisLineShow= false, ) => ({
  data,
  axisLine: {
    show: axisLineShow,
    lineStyle: {
      color: "#fff",
    },
  },
  axisLabel: {
    show: labelShow,
    lineStyle: {
      color: "#fff",
    },
    nameTextStyle: {
      color: "#fff",
      fontSize: '9',
    },
  },
  axisTick: {
    show: false,
  },
});

const getSeries = (name,data, xAxisIndex = 0, barWidth = 40, color = '#153238') => {
  const base = {
    type: "bar",
    data,
    barWidth,
    xAxisIndex,
  }
  let other = {};
  if (xAxisIndex) {
    other = {
      name,
      itemStyle: {
        color,
      },
    };
  } else {
    other = {
      silent: true,
      tooltip: {
        show: false,
      },
    }
  }
  return { ...base, ...other };
};

const getAreaSeries = (name, data,barWidth, color,yAxisIndex,z, areaData, otherOptions) => {
  const options = {
    type: "bar",
    data,
    barWidth,
    itemStyle: {
      color,
    },
    z,
    yAxisIndex,
  };
  let other = {};
  if (!name) {
    other = {
      label: {
        normal: {
          show: true,
          color: '#fff',
          fontSize: 10,
          borderColor: 'none',
          position: ['85%', '-35%'],
          formatter: function (data) {
            // console.log(data)
            const { dataIndex,data:value }= data;
            // const res = areaData?.[dataIndex];
            // const {output,throughput} = res;
            // return `${throughput}/${output}`;
            return `${value}`;
          },
        },
      }
    }
  }
  return {...options, ...otherOptions, ...other};
};

export default {
  props: {
    data: {
      type: Object,
      default: () => ({}),
    }
  },
  data() {
    return {
      areaChart: null,
      timeChart: null,
      options: [
        {
          name: '',
          value: '',
          color: '#153238',
          barWidth: '15%',
          areaBarWidth: '35%',
          xAxisIndex: 0,
          labelShow: true,
          z: 1,
        },
        // {
        //   name: '总产生量',
        //   value: 'throughput',
        //   color: '#66bbf9',
        //   barWidth: 12,
        //   areaBarWidth: '15%',
        //   xAxisIndex: 1,
        //   z: 2,
        //   getOtherOptions: (list) => ({
        //     label: {
        //       normal: {
        //         show: true,
        //         color: '#fff',
        //         fontSize: 10,
        //         borderColor: 'none',
        //         position: ['0%', '-190%'],
        //         formatter: function (data) {
        //           const { dataIndex }= data;
        //           const res = list?.[dataIndex];
        //           return `${res}`;
        //         },
        //       },
        //     }
        //   })
        // },
        {
          name: '已处理',
          value: 'output',
          color: '#87f7c7',
          // barWidth: 12,
          barWidth: '15%',
          // areaBarWidth: '15%',
          areaBarWidth: '35%',
          xAxisIndex: 1,
          z: 2,
            getOtherOptions: (list) => ({
              label: {
                normal: {
                  show: true,
                  color: '#fff',
                  fontSize: 12,
                  borderColor: 'none',
                  position: ['0%', '-35%'],
                  formatter: function (data) {
                    const { dataIndex }= data;
                    const res = list?.[dataIndex];
                    return `${res}`;
                  },
                },
              }
            })
        },
      ],
    };
  },
  computed: {
    xAxisInfo() {
      // return Object.keys(this.data).reduce((acc,key) => {
      //   if (isNaN(Number(key))) acc.area.push(key);
      //   else acc.time.push(key);
      //   return acc;
      // }, {time: [], area: []});
      const data = this.data;
      return Object.keys(data).reduce((acc,key) => {
        if (key === 'area') acc.area = Object.keys(data[key]);
        if (key === 'all') acc.time = Object.keys(data[key]);
        return acc;
      }, {});
    },
    timeXAxis() {
      return (this.xAxisInfo.time || []).map(item => `${item}日`);
    },
    areaXAxis() {
      return this.xAxisInfo.area || [];
    },
    seriesData() {
      const result = this.data;
      return Object.keys(result).reduce((acc,key) => {
        const value = result[key];
        const values = Object.values(value);
        // if (isNaN(Number(key))) acc.area.push(value);
        // else acc.time.push(value);
        if (key === 'area') acc.area = values;
        if (key === 'all') acc.time = values;
        return acc;
      }, {time: [],area: [],});
    },
    timeData() {
      return this.seriesData.time || [];
    },
    maxTimeData() {
      // const data = this.timeData.map(item => Math.max(item.throughput, item.output));
      // return Math.max(...data)
      return Math.max(...this.timeData);
    },
    areaData() {
      return this.seriesData.area || [];
    },
    maxAreaData() {
      // const data = this.areaData.map(item => Math.max(item.throughput, item.output));
      // return Math.max(...data)
      return Math.max(...this.areaData);
    },
  },
  watch: {
    timeData() {
      this.onInitTimeBar();
    },
    areaData() {
      this.onInitAreaChart();
    },
  },
  mounted() {
    this.onInitChart();
    this.onBus();
    window.addEventListener('resize', this.resizeChart);
  },
  beforeDestroy() {
    this.$bus.$off('resize', this.onChangeReSize);
    this.$bus.$off('changeIsPackUp', this.onChangeIsPackUp);
    window.removeEventListener('resize', this.onChangeReSize);
  },
  methods: {
    resizeChart() {
      if (this.timeChart) this.timeChart.resize();
      if (this.areaChart) this.areaChart.resize();
    },
    onBus() {
      this.$bus.$on('resize',this.onChangeReSize);
      this.$bus.$on('changeIsPackUp', this.onChangeIsPackUp);
    },
    onChangeIsPackUp(val) {
      if (val) return false;
      setTimeout(() => {
        this.resizeChart();
      }, 500)
    },
    onChangeReSize() {
      this.timeChart.resize();
      this.areaChart.resize();
    },
    onInitChart() {
      this.timeChart = echarts.init(this.$refs.time);
      this.areaChart = echarts.init(this.$refs.area);
    },
    onInitTimeBar() {
      const baseOptions = getBaseOptions();
      const infoOptions = this.options;
      const xAxis = infoOptions.map((item,index) => getBaseXAxis(this.timeXAxis, item.labelShow || false,!index));
      // const series = infoOptions.map(item => {
      //   const { name, xAxisIndex,barWidth, color,value:key } = item;
      //   let data = [];
      //   if (key) data = this.timeData || [];
      //   else data = new Array(this.timeData.length).fill(this.maxTimeData + 50);
      //   return getSeries(name,data, xAxisIndex, barWidth, color);
      // });
      const series = [
        {
          "type": "bar",
          "data": this.timeData,
          "barWidth": "15%",
          // "xAxisIndex": 1,
          "name": "已处理",
          "itemStyle": {
            normal: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: "#0090FF",

                },
                {
                  offset: 1,
                  color: "#041538",
                },
              ]),
              barBorderRadius: [12,12,0,0],
            },
          },
        }
      ];
      const options = { ...baseOptions, xAxis, series };
      this.timeChart.setOption(options)
    },
    onInitAreaChart() {
      const baseOptions = {
        color: ["#153238"],
        xAxis: {
          "axisLine": {
            "show": false
          },
          "axisLabel": {
            "show": false
          },
          "axisTick": {
            "show": false
          },
          "splitLine": {
            "show": false
          }
        },
        grid: {
          left: '0%',
          right: '0%',
          bottom: '0%',
          top: '4%',
          containLabel: true
        },
      };
      const infoOptions = this.options;
      const yAxis = infoOptions.map(() =>  getBaseXAxis(this.areaXAxis, false));
      const series = infoOptions.map(item => {
        const { name, xAxisIndex,areaBarWidth,z, color,value:key, getOtherOptions } = item;
        let data = [];
        // if (key) data = this.areaData.map(i => +(i[key] || 0));
        const maxLen = this.maxAreaData + 50 > 100 ? 100 : this.maxAreaData + 50;
        const seriesName = key ? '已处理' : '峰值';
        if (key) data = this.areaData || [];
        else data = new Array(this.areaData.length).fill(maxLen);
        const otherOptions = getOtherOptions?.(this.areaXAxis) ?? {};
        const res = getAreaSeries(name,data, areaBarWidth,color,xAxisIndex,z ,this.areaData, otherOptions);
        return {...res,barWidth: '15%',name:seriesName}
      });
      series[1].itemStyle = {
        normal: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: "#0090FF",

            },
            {
              offset: 1,
              color: "rgba(0, 144, 255, 0.1)",
            },
          ]),
          barBorderRadius: [0,12,12,0],
        },
      }
      const that = this;
      series[0].label = {
        show: true,
        fontSize:10,
        color:"#fff",
        position: ['85%', '-120%'],
        formatter: function (data) {
          const {dataIndex,data: max} = data;
          const value = that.areaData[dataIndex];
          return `${value}/${max}`
        }
      };
      series[1].label = {
        show: true,
        fontSize:10,
        color:"#fff",
        position: ['0%', '-120%'],
        formatter: function (data) {
          const {name} = data;
          return name;
        }
      }
      const legend = {
        legend: {
          data: ['已处理'],
          bottom: "0%",
          textStyle: {
            color: "#a4a8b4",
          },
        },
      }
      const options = { ...baseOptions, yAxis, series,...legend};
      this.areaChart.setOption(options)
    },
  },
}
</script>

<style scoped lang="scss">
.sanitationStation-box {
  min-width:  200px;
  height: 100%;
  position: relative;
  & > div {
    width: 100%;
  }
}
</style>
